<template>
  <view class="dice-page">
    <!-- 骰子输入区域 -->
    <view class="dice-input-section">
      <view class="input-container">
        <input 
          v-model="diceCommand" 
          placeholder="输入骰子指令，如：.r 1d100 或 .check 侦查 70"
          class="dice-input"
          @confirm="rollDice"
          :disabled="isRolling"
        />
        <button 
          class="roll-btn" 
          @click="rollDice"
          :disabled="!diceCommand.trim() || isRolling"
        >
          {{ isRolling ? '掷骰中...' : '掷骰' }}
        </button>
      </view>
      
      <!-- 快速指令按钮 -->
      <view class="quick-commands">
        <button 
          v-for="cmd in quickCommands" 
          :key="cmd.command"
          class="quick-btn"
          @click="setCommand(cmd.command)"
        >
          {{ cmd.label }}
        </button>
      </view>
    </view>

    <!-- 3D骰子动画区域 -->
    <view class="dice-animation" v-if="showAnimation">
      <view class="dice-container">
        <view 
          v-for="(dice, index) in animationDice" 
          :key="index"
          class="dice-3d"
          :style="dice.style"
        >
          {{ dice.value }}
        </view>
      </view>
    </view>

    <!-- 摇一摇掷骰 -->
    <view class="shake-section">
      <button 
        class="shake-btn"
        @click="toggleShakeMode"
        :class="{ 'active': shakeMode }"
      >
        {{ shakeMode ? '摇一摇已开启' : '开启摇一摇掷骰' }}
      </button>
      <text class="shake-tip" v-if="shakeMode">摇动手机进行掷骰</text>
    </view>

    <!-- 骰子历史记录 -->
    <view class="dice-history">
      <view class="history-header">
        <text class="history-title">掷骰历史</text>
        <button 
          class="clear-btn" 
          @click="clearHistory"
          :disabled="diceHistory.length === 0"
        >
          清空
        </button>
      </view>
      
      <scroll-view class="history-list" scroll-y>
        <view 
          v-for="(record, index) in diceHistory" 
          :key="index"
          class="history-item"
          :class="{ 'success': record.isSuccess, 'failure': record.isSuccess === false }"
        >
          <view class="history-time">{{ formatTime(record.timestamp) }}</view>
          <view class="history-command">{{ record.command }}</view>
          <view class="history-result">{{ record.formattedResult }}</view>
          <view class="history-details" v-if="record.details">
            <text 
              v-for="(detail, i) in record.details" 
              :key="i" 
              class="detail-item"
            >
              {{ detail }}
            </text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 响应式数据
const diceCommand = ref('')
const isRolling = ref(false)
const showAnimation = ref(false)
const animationDice = ref([])
const shakeMode = ref(false)
const diceHistory = ref([])

// 快速指令
const quickCommands = ref([
  { label: '1d100', command: '.r 1d100' },
  { label: '2d6', command: '.r 2d6' },
  { label: '1d20', command: '.r 1d20' },
  { label: '侦查检定', command: '.check 侦查 70' },
  { label: '聆听检定', command: '.check 聆听 60' },
  { label: '潜行检定', command: '.check 潜行 50' }
])

// 骰子解析器（简化版）
const parseDiceCommand = (command) => {
  const trimmedCommand = command.trim()
  
  // 技能检定
  const checkMatch = trimmedCommand.match(/^\.check\s+(\w+)\s+(\d+)$/)
  if (checkMatch) {
    const skillName = checkMatch[1]
    const skillValue = parseInt(checkMatch[2])
    const diceResult = Math.floor(Math.random() * 100) + 1
    const isSuccess = diceResult <= skillValue
    
    let successLevel = '失败'
    if (isSuccess) {
      if (diceResult <= Math.floor(skillValue / 5)) {
        successLevel = '极难成功'
      } else if (diceResult <= Math.floor(skillValue / 2)) {
        successLevel = '困难成功'
      } else {
        successLevel = '普通成功'
      }
    }
    
    return {
      type: 'check',
      skillName,
      skillValue,
      diceResult,
      isSuccess,
      successLevel,
      command: `.check ${skillName} ${skillValue}`,
      formattedResult: `${skillName}检定: ${diceResult}/${skillValue} ${isSuccess ? successLevel : '失败'}`
    }
  }
  
  // 掷骰指令
  const diceMatch = trimmedCommand.match(/^\.r\s+(\d+d\d+(?:\+\d+d\d+)*(?:\+\d+)?)$/)
  if (diceMatch) {
    const diceString = diceMatch[1]
    const parts = diceString.split('+')
    const diceResults = []
    let total = 0
    
    for (const part of parts) {
      const trimmedPart = part.trim()
      
      if (trimmedPart.includes('d')) {
        const [count, sides] = trimmedPart.split('d').map(Number)
        const rolls = []
        let partTotal = 0
        
        for (let i = 0; i < count; i++) {
          const roll = Math.floor(Math.random() * sides) + 1
          rolls.push(roll)
          partTotal += roll
        }
        
        diceResults.push({
          type: 'dice',
          count,
          sides,
          rolls,
          total: partTotal,
          display: `${count}d${sides}`
        })
        total += partTotal
      } else {
        const bonus = parseInt(trimmedPart)
        diceResults.push({
          type: 'bonus',
          value: bonus,
          display: `+${bonus}`
        })
        total += bonus
      }
    }
    
    const partsStr = diceResults.map(dr => {
      if (dr.type === 'dice') {
        return `${dr.display}(${dr.rolls.join(', ')})`
      } else {
        return dr.display
      }
    }).join(' + ')
    
    return {
      type: 'dice',
      diceResults,
      total,
      command: `.r ${diceString}`,
      formattedResult: `${partsStr} = ${total}`
    }
  }
  
  throw new Error('无效的骰子指令格式')
}

// 方法
const setCommand = (command) => {
  diceCommand.value = command
}

const rollDice = async () => {
  if (!diceCommand.value.trim() || isRolling.value) return

  try {
    isRolling.value = true
    showAnimation.value = true

    // 解析骰子指令
    const result = parseDiceCommand(diceCommand.value)
    
    // 生成动画骰子
    generateAnimationDice(result)
    
    // 等待动画完成
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 创建记录
    const record = {
      command: result.command,
      result: result,
      formattedResult: result.formattedResult,
      timestamp: new Date(),
      isSuccess: result.isSuccess,
      details: generateResultDetails(result)
    }

    // 添加到历史记录
    diceHistory.value.unshift(record)
    if (diceHistory.value.length > 100) {
      diceHistory.value = diceHistory.value.slice(0, 100)
    }
    
    // 清空输入
    diceCommand.value = ''
    
    // 隐藏动画
    showAnimation.value = false
    
    uni.showToast({
      title: '掷骰完成',
      icon: 'success'
    })
    
  } catch (error) {
    uni.showToast({
      title: error.message,
      icon: 'error'
    })
    showAnimation.value = false
  } finally {
    isRolling.value = false
  }
}

const generateAnimationDice = (result) => {
  animationDice.value = []
  
  if (result.type === 'dice') {
    for (const diceResult of result.diceResults) {
      if (diceResult.type === 'dice') {
        for (let i = 0; i < diceResult.count; i++) {
          animationDice.value.push({
            value: diceResult.rolls[i],
            style: {
              left: Math.random() * 200 + 'px',
              top: Math.random() * 100 + 'px',
              animationDelay: Math.random() * 0.5 + 's'
            }
          })
        }
      }
    }
  } else if (result.type === 'check') {
    animationDice.value.push({
      value: result.diceResult,
      style: {
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)'
      }
    })
  }
}

const generateResultDetails = (result) => {
  const details = []
  
  if (result.type === 'dice') {
    for (const diceResult of result.diceResults) {
      if (diceResult.type === 'dice') {
        details.push(`${diceResult.display}: ${diceResult.rolls.join(', ')}`)
      } else {
        details.push(diceResult.display)
      }
    }
  } else if (result.type === 'check') {
    details.push(`技能值: ${result.skillValue}`)
    details.push(`成功等级: ${result.successLevel}`)
  }
  
  return details
}

const formatTime = (timestamp) => {
  return timestamp.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const clearHistory = () => {
  diceHistory.value = []
  uni.showToast({
    title: '历史记录已清空',
    icon: 'success'
  })
}

const toggleShakeMode = () => {
  shakeMode.value = !shakeMode.value
  
  if (shakeMode.value) {
    // 开启摇一摇监听
    uni.onAccelerometerChange((res) => {
      const { x, y, z } = res
      const acceleration = Math.sqrt(x * x + y * y + z * z)
      
      if (acceleration > 2) {
        // 检测到摇动
        if (diceCommand.value.trim()) {
          rollDice()
        } else {
          diceCommand.value = '.r 1d100'
          rollDice()
        }
      }
    })
    
    uni.startAccelerometer({
      interval: 'normal'
    })
  } else {
    // 关闭摇一摇监听
    uni.stopAccelerometer()
  }
}

// 生命周期
onMounted(() => {
  // 组件挂载时的初始化
})

onUnmounted(() => {
  // 组件卸载时停止摇一摇监听
  if (shakeMode.value) {
    uni.stopAccelerometer()
  }
})
</script>

<style scoped>
.dice-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.dice-input-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.input-container {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.dice-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #ddd;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.roll-btn {
  width: 120rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.roll-btn:disabled {
  background: #ccc;
}

.quick-commands {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.quick-btn {
  padding: 15rpx 25rpx;
  background: #f0f9ff;
  color: #667eea;
  border: 2rpx solid #667eea;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.dice-animation {
  height: 300rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  position: relative;
  overflow: hidden;
}

.dice-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.dice-3d {
  position: absolute;
  width: 60rpx;
  height: 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 24rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.2);
  animation: diceRoll 2s ease-out forwards;
}

@keyframes diceRoll {
  0% {
    transform: translateY(-200rpx) rotateX(0deg) rotateY(0deg);
    opacity: 0;
  }
  50% {
    transform: translateY(0) rotateX(180deg) rotateY(180deg);
    opacity: 1;
  }
  100% {
    transform: translateY(0) rotateX(360deg) rotateY(360deg);
    opacity: 1;
  }
}

.shake-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.shake-btn {
  padding: 20rpx 40rpx;
  background: #f0f9ff;
  color: #667eea;
  border: 2rpx solid #667eea;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.shake-btn.active {
  background: #667eea;
  color: white;
}

.shake-tip {
  display: block;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.dice-history {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #eee;
}

.history-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.clear-btn {
  padding: 10rpx 20rpx;
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.clear-btn:disabled {
  background: #ccc;
}

.history-list {
  max-height: 600rpx;
}

.history-item {
  padding: 20rpx;
  margin-bottom: 15rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border-left: 6rpx solid #ddd;
}

.history-item.success {
  border-left-color: #67c23a;
  background: #f0f9ff;
}

.history-item.failure {
  border-left-color: #f56c6c;
  background: #fef0f0;
}

.history-time {
  font-size: 20rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.history-command {
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  font-size: 28rpx;
}

.history-result {
  color: #666;
  font-size: 26rpx;
  margin-bottom: 15rpx;
}

.history-details {
  font-size: 22rpx;
  color: #888;
}

.detail-item {
  display: block;
  margin-bottom: 4rpx;
}
</style>
